/*
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
*/
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class SimpleServerThread extends Thread {

	public SimpleServerThread() {
		super("SimpleServerThread");
		
	}


	public void run() {
		DatagramSocket socket = null;
		try {
			System.out.println(InetAddress.getLocalHost().toString());
			socket = new DatagramSocket(4445, InetAddress.getByName("localhost"));
		} catch (Exception e) {
			System.err.println("Could not listen on port: 4445.");
			System.exit(-1);
		}

		try {
			boolean listening = true;
			int count = 0;
			while(listening) {
				byte[] buf = new byte[256];
				System.out.println("Started, waiting for packets (processed " + count + ") already...");
				DatagramPacket packet = new DatagramPacket(buf, buf.length);
				socket.receive(packet);
	
				String outputString = "You sent: " + new String(packet.getData(), "Cp1252" /* encoding */);
				System.out.println(outputString);
				InetAddress address = packet.getAddress();
	            int port = packet.getPort();
	            byte[] outBuf = outputString.getBytes("UTF8");
	            packet = new DatagramPacket(outBuf, outBuf.length, address, port);
	            socket.send(packet);
	            System.out.println("Packet sent");
	            count++;
			}
            
            socket.close();
            System.out.println("Socket closed");
			/*
			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
			BufferedReader in = new BufferedReader(
					new InputStreamReader(
					socket.getInputStream()));
			
			String inputLine, outputLine;
			
			SimpleProtocol smp = new SimpleProtocol();
			outputLine = smp.processInput(null);
			out.println(outputLine);
			
			while ((inputLine = in.readLine()) != null) {
				outputLine = smp.processInput(inputLine);
				out.println(outputLine);
				if (outputLine.equals("Bye")) {
					break;
				}
			}
			out.close();
			in.close();
			socket.close();
			*/
		} catch (Exception e) {
			System.out.println("SimpleServerThread Message: " + e.getMessage());
			e.printStackTrace();
		}
		
	}
}